from tkinter import *
from tkinter import ttk
from tkinter import messagebox  # 引入用于弹出确认消息框
from openpyxl import load_workbook
import main  # 引入主界面模块
import config  # 引入配置文件模块
import os
import sys
import Lock  # 引入进程锁模块

# 配置文件实例化
config_instance = config.Path_Config()
# 初始化锁文件路径
app_editcontext_lock_file = config_instance.resource_path('Editcontext.lock')
# 锁配置实例化
lock = Lock.ProcessLock(app_editcontext_lock_file)


class Mainwindow(Tk):
    """
    基础主窗口，包含空菜单栏、工具栏、状态栏和主框架。
    """
    
    def __init__(self) -> None:
        super().__init__()
        if lock.is_running():
            sys.exit(1)  # 如果已有实例在运行，则退出当前程序
        # 尝试加载临时数据文件
        try:
            self.wb = load_workbook(config_instance.temp_xlsx)
            self.titlemsg = '-已加载上次修改'
        except FileNotFoundError:
            # 如果找不到临时文件，就加载源数据文件
            self.wb = load_workbook(config_instance.source_xlsx)
            self.titlemsg = '-未能加载临时文件'

        self.sheet1 = self.wb['Sheet1']

        # 初始化工具栏、主框架和状态栏
        self.toolbar = ttk.Frame(self, padding='3 3 3 3')
        self.mainframe = ttk.Frame(self, padding='3 3 3 3')
        self.statusbar = ttk.Frame(self, padding='3 3 3 0')

        # 设定表头
        pre_list = ['总序', '表序', '表名', '表左侧标题', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
                    '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
        self.header = pre_list[:self.sheet1.max_column]

        # 布局
        self.toolbar.grid(column=0, row=0, sticky=NSEW)
        self.mainframe.grid(column=0, row=1, sticky=NSEW)
        self.statusbar.grid(column=0, row=2, sticky=NSEW)
        self.option_add('*tearOff', FALSE)

        # 创建菜单栏
        self.menubar = Menu(self)
        self['menu'] = self.menubar

        # 状态消息
        self.statusmsg = StringVar()
        self.statusLabel = Label(self.statusbar, textvariable=self.statusmsg)
        self.statusLabel.grid(column=0, row=0, sticky=SW)

        # 配置大小
        self.toolbar.rowconfigure(0, weight=1)
        self.statusbar.columnconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)

        # 添加保存并返回按钮
        self.save_button = Button(self.toolbar, text="保存并返回", command=self.save_and_return)
        self.save_button.pack(side=LEFT)

        # 添加增行按钮
        self.add_row_button = Button(self.toolbar, text="增行", command=self.add_row)
        self.add_row_button.pack(side=RIGHT)

        # 添加减行按钮
        self.delete_row_button = Button(self.toolbar, text="减行", command=self.delete_selected_item)
        self.delete_row_button.pack(side=RIGHT)

        # 添加打开文件按钮
        self.open_excel_button = Button(self.toolbar, text="打开Excel直接编辑", command=self.open_excel_file)
        self.open_excel_button.pack(side=TOP)
<<<<<<< HEAD
=======

        # 绑定关闭窗口事件
        self.protocol("WM_DELETE_WINDOW", self.on_close)
>>>>>>> refs/remotes/origin/main
 
    def open_excel_file(self):
        if os.path.exists(config_instance.temp_xlsx):
            messagebox.showinfo("提示", "已加载上次修改")
            os.startfile(config_instance.temp_xlsx)
        else:
            messagebox.showinfo("提示", "未找到上次修改，已打开源文件")
            os.startfile(config_instance.source_xlsx)
        self.switch_to_main_app()

<<<<<<< HEAD
=======
    def on_close(self):
        self.destroy()  # 销毁当前窗口
        # 程序退出时删除锁文件
        if os.path.exists(app_editcontext_lock_file):
            os.remove(app_editcontext_lock_file)

>>>>>>> refs/remotes/origin/main

    def add_row(self):
        selected_item = self.tree.selection()
        if selected_item:
            selected_index = self.tree.index(selected_item[0])
            # 获取选中行的值
            selected_values = self.tree.item(selected_item[0], 'values')
            # 创建新行，前三列值与选中行相同，其他列为空
            new_row_values = list(selected_values[:3]) + [''] * (len(self.header) - 3)
            # 在选中行的上一行插入新行
            self.tree.insert('', selected_index, values=new_row_values)  # 在树形控件中插入新行
            # 在 Excel 中插入新行
            self.sheet1.insert_rows(selected_index + 2)  # Excel 行索引（Excel 行由1开始，且标题在第一行）
        # 根据需要更新新插入的行的前3列
            for i in range(3):
                self.sheet1.cell(row=selected_index + 2, column=i + 1, value=new_row_values[i])
            self.wb.save(self.temp_xlsx)  # 保存修改

    def delete_selected_item(self):
        selected_item = self.tree.selection()
        if selected_item:
            # 询问用户确认删除
            confirm = messagebox.askyesno("确认删除", "你确定要删除选中行吗？")
            if confirm:
                row_index = self.tree.index(selected_item[0]) + 2  # Excel 行号计算
                self.tree.delete(selected_item[0])  # 删除树结构中的行
                self.sheet1.delete_rows(row_index)  # 从 Excel 中删除对应的行
                self.wb.save(self.temp_xlsx)  # 保存修改

    def save_and_return(self):
        """保存修改并返回主界面"""
        self.wb.save(config_instance.source_xlsx)  # 保存为源文件
        self.switch_to_main_app()  # 切换到主界面

    def switch_to_main_app(self):
        """切换回主界面"""
        self.destroy()  # 销毁当前窗口
        # 删除锁文件
        os.remove(app_editcontext_lock_file)
        main.ReportEditor().mainloop()  # 创建主界面实例

    def showmessage(self, msg: str):
        self.statusmsg.set(msg)


class EditExcel(Mainwindow):
    def __init__(self):
        super().__init__()
        self.title('编辑template' + self.titlemsg)
        self.geometry('1280x720')

        self.tree = ttk.Treeview(self.mainframe, height=15, columns=self.header, show='headings')
        for col in self.header:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=100, anchor='center', stretch=True)

        self.YScroll = ttk.Scrollbar(self.mainframe, orient=VERTICAL, command=self.tree.yview)
        self.XScroll = ttk.Scrollbar(self.mainframe, orient=HORIZONTAL, command=self.tree.xview)
        self.tree.grid(column=0, row=0, sticky=NSEW)
        self.YScroll.grid(column=1, row=0, sticky=NS)
        self.XScroll.grid(column=0, row=1, sticky=EW)

        self.mainframe.rowconfigure(0, weight=1)
        self.mainframe.columnconfigure(0, weight=1)

        self.init_tree()
        self.delegate_var = StringVar()
        self.tree.bind('<Double-1>', self.tree_item_edit)

        self.showmessage('Ready.')

    def readDataSet(self):
        contents = []
        for row in self.sheet1.iter_rows(min_row=2, values_only=True):
            row_val = [col if col is not None else ' ' for col in row]
            contents.append(row_val)
        return contents

    def init_tree(self):
        contents = self.readDataSet()
        for row in contents:
            self.tree.insert("", "end", values=row)

    def tree_item_edit(self, e: Event):
        selected_item = self.tree.selection()
        if not selected_item:
            return

        self.selected_item = selected_item[0]
        for i, col in enumerate(self.tree['columns']):
            x, y, w, h = self.tree.bbox(self.selected_item, col)
            if x < e.x < x + w and y < e.y < y + h:
                self.selected_column = col
                text = self.tree.item(self.selected_item, 'values')[i] or ' '
                break
        else:
            self.selected_column = None
            x, y, w, h = self.tree.bbox(self.selected_item)
            text = self.tree.item(self.selected_item, 'text')

        self.delegate_var.set(text)
        self.create_delegate_widget(x, y, w)
        self.delegate_widget.focus()

    def create_delegate_widget(self, x, y, w):
        if self.selected_column == self.header[1]:  
            self.delegate_widget = ttk.Spinbox(self.tree, width=w // 8, textvariable=self.delegate_var, from_=1, to=100)
        else:
            self.delegate_widget = ttk.Entry(self.tree, width=w // 8, textvariable=self.delegate_var)

        self.delegate_widget.grid(padx=x, pady=y)
        self.delegate_widget.bind('<FocusOut>', self.tree_item_edit_done)

    def tree_item_edit_done(self, e):
        self.delegate_widget.grid_forget()
        edited_value = self.delegate_var.get()

        # 更新树形视图
        if self.selected_column is None:
            self.tree.item(self.selected_item, text=edited_value)
        else:
            self.tree.set(self.selected_item, self.selected_column, edited_value)

        # 生成临时文件缓存修改
        row_index = self.tree.index(self.selected_item) + 2  # Excel 行号计算
        col_index = self.header.index(self.selected_column) + 1  # Excel 列号计算
        self.sheet1.cell(row=row_index, column=col_index, value=edited_value)
        self.wb.save(config_instance.temp_xlsx)

if __name__ == '__main__':
    mw = EditExcel()
    mw.mainloop()
    # 程序结束时删除锁文件
    if os.path.exists(app_editcontext_lock_file):
        os.remove(app_editcontext_lock_file)